import logging

from bson.objectid import ObjectId

from tornado.web import RequestHandler
from tornado.web import authenticated

from tornado.gen import coroutine
from tornado.web import asynchronous

from handlers import BaseHandler, UserBaseHandler
from handlers.admin import AdminBaseHandler


class MyHandler(UserBaseHandler):

    @coroutine
    def get(self):
        username = self.current_user.get('username')

        cur_apps_ing = self.db.apps.find({"reseach.initiator": username, "status": 0})
        apps_ing = yield cur_apps_ing.to_list(12)

        cur_apps_close = self.db.apps.find({"reseach.initiator": username, "status": -10})
        apps_close = yield cur_apps_close.to_list(12)

        self.render('apps/my.html', apps_ing=apps_ing, apps_close=apps_close)


class DetailHandler(UserBaseHandler):

    @coroutine
    def get(self, id):

        detail = yield self.db.apps.find_one({"_id": ObjectId(id)})

        self.render('apps/detail.html', detail=detail)

#########
#admin
########


class ListAdminHandler(AdminBaseHandler):

    @coroutine
    def get(self):

        cur_apps_ing = self.db.apps.find({"status": 0})
        apps_ing = yield cur_apps_ing.to_list(12)

        cur_apps_close = self.db.apps.find({"status": -10})
        apps_close = yield cur_apps_close.to_list(12)

        self.render('admin/app/index.html', apps_ing=apps_ing, apps_close=apps_close)

class DetailAdminHandler(AdminBaseHandler):

    @coroutine
    def get(self, id):

        detail = yield self.db.apps.find_one({"_id": ObjectId(id)})

        self.render('admin/app/detail.html', detail=detail)
